<template>
  <div class="question-show">
    <el-row type="flex" justify="space-around" style="margin-top:16px;">
      <!-- xs	<768px 响应式栅格数或者栅格属性对象
           sm	≥768px 响应式栅格数或者栅格属性对象
           md	≥992px 响应式栅格数或者栅格属性对象
           lg	≥1200px 响应式栅格数或者栅格属性对象
           xl	≥1920px 响应式栅格数或者栅格属性对象 -->
      <el-col :xs="22" :sm="12" :md="10">
        <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);padding-bottom:2px;">
          <div style="text-align:center;margin-bottom:8px;padding-top:8px;">
            <label>{{ question.questionCaption }}</label>
          </div>
          <div style="margin:0 24px 8px 24px;">
            <div v-html="question.questionExplain" />
          </div>
        </div>
        <div>
          <div v-for="(item, index) in questionDetailList" :key="item.detailId" style="margin-top:8px;padding:8px 8px 0px 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);">
            <div v-if="item.questionType !== 'explain'">
              <label v-if="item.required === '1'" style="color:red;">*</label>
              <span style="font-size:14px;">{{ item.indexOrder + '.' }}</span>
              <span v-html="'&nbsp;'" />
              <span style="font-size:14px;">{{ item.caption }}</span>
              <span v-html="'&nbsp;'" />
              <span style="font-weight:bold;font-size:14px;">{{ item.questionTypeName }}</span>
            </div>
            <div v-if="item.questionType === 'choice'" class="rdb-choice">
              <el-radio-group v-model="answerList[index].answerDetailList[0]">
                <el-radio
                  v-for="(detail1) in item.questionDetailItemList"
                  :key="detail1.itemId"
                  :label="detail1.itemId"
                >{{ detail1.optionName }}</el-radio>
              </el-radio-group>
            </div>
            <div v-if="item.questionType === 'multiple-choice'" class="chk-multi-choice">
              <el-checkbox-group v-model="answerList[index].answerDetailList">
                <el-checkbox
                  v-for="(detail2) in item.questionDetailItemList"
                  :key="detail2.itemId"
                  :label="detail2.itemId"
                >{{ detail2.optionName }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-if="item.questionType === 'fill-blank'" style="padding:4px 0px 6px 12px;font-size:14px;line-height:28px;">
              <span v-for="(detail3, index3) in item.questionDetailItemList" :key="detail3.itemId">
                <template v-if="detail3.optionClass === 'next-line'">
                  <br>
                </template>
                <template v-else>
                  <template v-if="detail3.optionClass === 'fill-blank'">
                    <el-input v-model="answerList[index].answerDetailList[index3].optionValue" class="underline-input" style="display: inline;" />
                  </template>
                  <template v-else>
                    <template v-if="detail3.optionClass === 'date'">
                      <el-date-picker
                        v-model="answerList[index].answerDetailList[index3].optionValue"
                        type="date"
                        placeholder="选择日期"
                        size="mini"
                        style="width: 140px;"
                      />
                    </template>
                    <template v-else>
                      {{ detail3.optionName }}
                    </template>
                  </template>
                </template>
              </span>
            </div>
            <div v-if="item.questionType === 'explain'" style="padding-bottom:8px;">
              <div v-html="item.caption" />
            </div>
          </div>
        </div>
        <div style="margin-top:20px;margin-bottom:20px;">
          <template v-if="status !== 'display'">
            <el-button style="width:100%;" type="primary" :disabled="status !== 'commit' || disabled" round @click="handleSubmitQuestion">提交问卷</el-button>
          </template>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getQuestionAndDetailById, validateQuestionLimit } from '@/api/questionnaire'
import { questionSort } from '@/utils/questionnaire-util'
import { saveAnswer, getAnswerListByAnswerMainId } from '@/api/answer'
const moment = require('moment')
export default {
  data() {
    return {
      status: 'preview',
      question: {},
      answerList: [],
      disabled: false
    }
  },
  computed: {
    questionDetailList: function() {
      return !this.question.questionDetailList ? [] : this.question.questionDetailList
    }
  },
  mounted: async function() {
    if (this.$route.query.questionId === undefined || this.$route.query.questionId === null || this.$route.query.questionId <= 0) {
      this.$router.replace('/404')
    }
    if (this.$route.query.status) {
      this.status = this.$route.query.status
    }
    const questionId = this.$route.query.questionId
    let params = {}
    // 检查一下是否可以继续提交问卷
    if (this.status === 'commit') {
      // 这里使用同步方法去判断
      await validateQuestionLimit({ questionId }).then(rr => {
        if (!rr.data) {
          this.$message({
            message: '您已经提交问卷,请勿重复提交!',
            type: 'success'
          })
          const { href } = this.$router.resolve({
            name: 'questionEnd'
          })
          window.open(href, '_self')
        }
      })
    }
    if (this.status === 'display') {
      // 这里使用同步方法去获取数据
      const mainId = this.$route.query.mainId
      await getAnswerListByAnswerMainId({
        mainId: mainId
      }).then(result => {
        params = result.data
      })
    }
    const that = this
    getQuestionAndDetailById({
      questionId
    }).then(res => {
      that.question = res.data
      questionSort(that.question)
      if (that.question && that.question.questionDetailList) {
        that.question.questionDetailList.forEach(aa => {
          if (aa.questionType === 'choice') {
            aa.questionTypeName = '【单选】'
            if (this.status === 'display') {
              this.answerList.push(this.handleAnswerList(params.list, aa.detailId))
            } else {
              this.answerList.push({
                questionType: aa.questionType,
                detailId: aa.detailId,
                answerDetailList: ['']
              })
            }
          } else if (aa.questionType === 'multiple-choice') {
            aa.questionTypeName = '【多选】'
            if (this.status === 'display') {
              this.answerList.push(this.handleAnswerList(params.list, aa.detailId))
            } else {
              this.answerList.push({
                questionType: aa.questionType,
                detailId: aa.detailId,
                answerDetailList: []
              })
            }
          } else if (aa.questionType === 'fill-blank') {
            aa.questionTypeName = '【填空】'
            const len = aa.questionDetailItemList ? aa.questionDetailItemList.length : 0
            const arr = []
            for (let idx = 0; idx < len; idx++) {
              let optionValue = ''
              // 从答卷里面获取结果 因为填空每一条数据都得绑定到answerList里面
              if (params.list) {
                const paramLength = params.list.length
                for (let paramIdx = 0; paramIdx < paramLength; paramIdx++) {
                  if (params.list[paramIdx].detailId === aa.detailId) {
                    if (params.list[paramIdx].answerDetailList) {
                      const detailLength = params.list[paramIdx].answerDetailList.length
                      for (let detailIdx = 0; detailIdx < detailLength; detailIdx++) {
                        if (params.list[paramIdx].answerDetailList[detailIdx].itemId === aa.questionDetailItemList[idx].itemId) {
                          optionValue = params.list[paramIdx].answerDetailList[detailIdx].optionValue
                          break
                        }
                      }
                    }
                    break
                  }
                }
              }
              arr.push({
                optionClass: aa.questionDetailItemList[idx].optionClass,
                optionValue: optionValue,
                itemId: aa.questionDetailItemList[idx].itemId
              })
            }
            this.answerList.push({
              questionType: aa.questionType,
              detailId: aa.detailId,
              answerDetailList: arr
            })
          } else {
            this.answerList.push({
              questionType: aa.questionType,
              detailId: aa.detailId,
              answerDetailList: []
            })
          }
        })
      }
    })
  },
  methods: {
    // 提交问卷
    handleSubmitQuestion: function() {
      this.disabled = true
      this.checkSubmitQuestion()
      const tempArr = JSON.parse(JSON.stringify(this.answerList)).filter(m => m.questionType !== 'explain')
      const len = tempArr.length
      for (let idx = 0; idx < len; idx++) {
        if (tempArr[idx].questionType === 'fill-blank') {
          tempArr[idx].answerDetailList = tempArr[idx].answerDetailList.filter(k => k.optionClass === 'fill-blank' || k.optionClass === 'date')
          const dateList = tempArr[idx].answerDetailList.filter(k => k.optionClass === 'date')
          if (dateList) {
            dateList.forEach(d => {
              d.optionValue = moment(d.optionValue).format('YYYY-MM-DD')
            })
          }
        } else {
          // 只是为了把itemId存上去
          const list = []
          tempArr[idx].answerDetailList.forEach(n => {
            list.push({
              itemId: n
            })
          })
          tempArr[idx].answerDetailList = list
        }
      }
      this.disabled = false
      saveAnswer({
        questionId: this.question.questionId,
        mainSessionId: this.question.uuid,
        answerList: tempArr
      }).then(res => {
        if (res.data) {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
          const { href } = this.$router.resolve({
            name: 'questionEnd'
          })
          window.open(href, '_self')
        }
        this.disabled = true
      }).catch(() => {
        this.disabled = true
      })
    },
    // 设置必填的是否都填了
    checkSubmitQuestion: function() {},
    // 返回上一层
    handleBackup() {
      this.$router.go(-1)
    },
    // 处理AnswerList
    handleAnswerList(answers, detailId) {
      const len = answers.length
      for (let kk = 0; kk <= len; kk++) {
        if (answers[kk].detailId === detailId) {
          if (answers[kk].questionType === 'choice') {
            let details = []
            if (answers[kk].answerDetailList && answers[kk].answerDetailList.length > 0) {
              details = [answers[kk].answerDetailList[0].itemId]
            }
            return {
              questionType: answers[kk].questionType,
              detailId: answers[kk].detailId,
              answerDetailList: details
            }
          } else if (answers[kk].questionType === 'multiple-choice') {
            const list = []
            if (answers[kk].answerDetailList) {
              answers[kk].answerDetailList.forEach(ll => {
                list.push(ll.itemId)
              })
            }
            return {
              questionType: answers[kk].questionType,
              detailId: answers[kk].detailId,
              answerDetailList: list
            }
          }
        }
      }
      return {}
    }
  }
}
</script>

<style lang="scss" scope>
.question-show {
  .rdb-choice {
    padding-left: 12px;
    .el-radio-group label{
      display: block;
      line-height: 28px;
    }
  }
  .chk-multi-choice {
    padding-left: 12px;
    .el-checkbox-group label {
      display: block;
      line-height: 28px;
    }
  }
  .underline-input {
    .el-input__inner {
      width: 160px;
      border-top-width: 0px;
      border-left-width: 0px;
      border-right-width: 0px;
      border-bottom-width: 1px;
      height: 26px;
      line-height: 26px;
    }
  }
}
</style>
